import requests
import json
import time
# from requests_toolbelt.multipart.encoder import MultipartEncoder
from threading import Thread


class regAndAuth():
    def __init__(self, login_url, register_jiami_url, register_url, auth_jiami_url, auth_url):
        self.login = login_url
        self.register_jiami_url = register_jiami_url
        self.register_url = register_url
        self.auth_jiami_url = auth_jiami_url
        self.auth_url = auth_url
        self.token = self.accessToken()

        self.headers_json = {
            'Authorization': self.token,
            'Content-Type': 'application/json'
        }
        self.headers_formdata = {
            'Authorization': self.token,
        }
        self.files = []

    def accessToken(self):
        """获取token"""
        headers = {
            'Content-Type': 'application/json'
        }
        payload_login = json.dumps({
            "username": "super_admin",
            "password": "5747cba9d15d3ad80507ed5b3cf84e25",
            "clientId": "frontend",
            "grantType": "password"
        })
        res = requests.request('POST', self.login, headers=headers, data=payload_login, verify=False).json()
        # print(res)
        # print( res['data']['accessToken'])
        return res['data']['accessToken']

    def reg(self):
        """注册加密 && 注册"""
        vehicleId = 1000000000000101
        while True:
            reg_payload_jiami = json.dumps({
                'oemCode': 'ECC17D16',
                'vehicleId': str(vehicleId+1),
                'cityCode': 'changchun',
                # 'networkLink':"4G",
                # 'grade':"L0",
                # 'category':"1",
            })
            response = requests.request("POST", self.register_jiami_url, headers=self.headers_json, data=reg_payload_jiami,
                                        verify=False).json()
            reg_jiami_data = response['data']

            payload_reg = {'data': reg_jiami_data}
            current_time = time.time()
            response = requests.request("POST", self.register_url, headers=self.headers_formdata, data=payload_reg,
                                        files=self.files,
                                        verify=False)
            gap_time = time.time() - current_time
            if time.time() - reg_start_time >= 60:
                break
            if gap_time > 0.3:
                reg_statistus_relay_list1.append(gap_time)
            if 1 - gap_time < 0:
                reg_statistus_relay_list.append(gap_time)
            else:
                reg_statistus_list.append(gap_time)
                time.sleep(1 - gap_time)


    def auth(self,):
        """授权加密 && 授权"""
        auth_payload_jiami = json.dumps({
            'oemCode': 'ECC17D16',
            'vehicleId': '0000000000000000',
            'refreshKey': "0",
            'type': 1,
            # 'networkLink':"4G",
            # 'grade':"L0",
            # 'category':"1",
        })

        response = requests.request("POST", self.auth_jiami_url, headers=self.headers_json, data=auth_payload_jiami,
                                    verify=False).json()
        auth_jiami_data = response['data']

        payload_auth = {'data': auth_jiami_data}
        while True:
            current_time = time.time()
            try:
                response = requests.request("POST", self.auth_url, headers=self.headers_formdata, data=payload_auth,
                                            files=self.files,
                                            verify=False)
            except Exception as e:
                print('响应报错,退出：', e)
                break
            gap_time = time.time() - current_time
            # print('%s授权响应时间：'.format(t),gap_time)
            if time.time() - start_time >= 60:
                break
            if gap_time > 0.3:
                statistus_relay_list1.append(gap_time)
            if 1 - gap_time < 0:
                statistus_relay_list.append(gap_time)
            else:
                statistus_list.append(gap_time)
                time.sleep(1 - gap_time)


if __name__ == '__main__':
    login_url = 'https://172.16.227.107:9001/v2x/platform/auth/user/login'
    register_jiami_url = "https://172.16.227.107:9001/v2x/platform/city/server/jiami"
    register_url = 'https://172.16.227.107:9001/v2x/platform/city/server/register'
    auth_jiami_url = "https://172.16.227.107:9001/v2x/platform/city/server/jiamiAuth"
    auth_url = 'https://172.16.227.107:9001/v2x/platform/city/server/auth'

    reg_and_auth = regAndAuth(login_url, register_jiami_url, register_url, auth_jiami_url, auth_url)

    # 统计授权请求时间
    statistus_list = []
    statistus_relay_list = []
    statistus_relay_list1 = []
    t_list = []
    start_time = time.time()
    for i in range(1):
        """10个线程1分钟请求600次"""
        t = Thread(target=reg_and_auth.auth)
        t.start()
        t_list.append(t)
    for j in t_list:
        j.join()
    print(statistus_list)
    print(statistus_relay_list)
    print(statistus_relay_list1)
    print('延迟在1s以内', len(statistus_list))
    print('延迟在1s以上', len(statistus_relay_list))
    print('延迟在300ms以上', len(statistus_relay_list1))
    with open('auth_relay.txt',mode='wt',encoding='utf8') as f:
        f.write(str(statistus_list))
        f.write(str(statistus_relay_list))
        f.write(str(statistus_relay_list1))
        f.write('延迟在1s以内' + str(len(statistus_list)))
        f.write('延迟在1s以上' + str(len(statistus_relay_list)))
        f.write('延迟在300ms以上' + str(len(statistus_relay_list1)))

    # 统计注册请求时间
    reg_statistus_list = []
    reg_statistus_relay_list = []
    reg_statistus_relay_list1 = []
    reg_t_list = []
    reg_start_time = time.time()
    for i in range(1):
        """1个线程1分钟请求600次"""
        t = Thread(target=reg_and_auth.reg)
        t.start()
        reg_t_list.append(t)
    for j in reg_t_list:
        j.join()
    print(reg_statistus_list)
    print(reg_statistus_relay_list)
    print(reg_statistus_relay_list1)
    print('延迟在1s以内', len(reg_statistus_list))
    print('延迟在1s以上', len(reg_statistus_relay_list))
    print('延迟在300ms以上', len(reg_statistus_relay_list1))
    with open('reg_relay.txt',mode='wt',encoding='utf8') as f:
        f.write(str(reg_statistus_list))
        f.write(str(reg_statistus_relay_list))
        f.write(str(reg_statistus_relay_list1))
        f.write('延迟在1s以内'+ str(len(reg_statistus_list)))
        f.write('延迟在1s以上' + str(len(reg_statistus_relay_list)))
        f.write('延迟在300ms以上' + str(len(reg_statistus_relay_list1)))





